package DAO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import Negocio.HojaDeRuta;

public class HibernateHojaDeRutaDAO {
	
	private static HibernateHojaDeRutaDAO instancia = null;
	private static SessionFactory sf = null;
	
	
	public static HibernateHojaDeRutaDAO getInstancia(){
		if(instancia == null){
			instancia = new HibernateHojaDeRutaDAO();
			sf = HibernateUtil.getSessionFactory();
		}
		return instancia;
	}
	
	public void grabarHojaRuta(HojaDeRuta hr){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(hr);
		session.flush();
		session.getTransaction().commit();
		session.close();
		}catch(Exception e){
			System.out.println(e);
			System.out.println("Error al grabar una Hoja de Ruta");
		}
	}
	
	public void updateHojaDeRuta(HojaDeRuta hr){
		try{
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(hr);
		session.flush();
		session.getTransaction().commit();
		session.close();
		}catch (Exception e){
			System.out.println(e);
            System.out.println("Error al actualizar la Hoja de Ruta");
		}
		
	}

	
	public HojaDeRuta getHojaDeRuta(int id){
        try {
        	Session session=sf.openSession();
            session.beginTransaction();
            Query q = session.createQuery("from HojaDeRuta h left join fetch h.viajes where h.idHojaDeRuta = ?").setInteger(0, id);
            HojaDeRuta hr = (HojaDeRuta) q.uniqueResult();
            session.getTransaction().commit();
            session.close();
            return hr;
        } catch (Exception e){
            System.out.println(e);
            System.out.println("Error al cargar una Hoja de Ruta");
        }
        return null;
	}

}
